using Microsoft.Extensions.Caching.Memory;
using System;
using System.Threading.Tasks;

namespace Services
{
    /// <summary>
    /// 内存缓存服务实现类
    /// </summary>
    public class MemoryCacheService : ICacheService
    {
        private readonly IMemoryCache _cache;
        /// <summary>
        /// 默认缓存过期时间（10分钟）
        /// </summary>
        private readonly TimeSpan _defaultExpiration = TimeSpan.FromMinutes(10);

        /// <summary>
        /// 构造函数，注入内存缓存服务
        /// </summary>
        public MemoryCacheService(IMemoryCache cache)
        {
            _cache = cache;
        }

        /// <summary>
        /// 获取或创建缓存项
        /// </summary>
        public async Task<T> GetOrCreateAsync<T>(string key, Func<Task<T>> factory, TimeSpan? expiration = null)
        {
            // 尝试从缓存获取
            if (_cache.TryGetValue(key, out T? cachedValue) && cachedValue != null)
            {
                return cachedValue;
            }

            // 缓存不存在，创建新值
            var value = await factory();
            if (value != null)
            {
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    .SetAbsoluteExpiration(expiration ?? _defaultExpiration);

                _cache.Set(key, value, cacheEntryOptions);
            }
            return value;
        }

        /// <summary>
        /// 移除缓存项
        /// </summary>
        public Task RemoveAsync(string key)
        {
            _cache.Remove(key);
            return Task.CompletedTask;
        }

        /// <summary>
        /// 检查缓存项是否存在
        /// </summary>
        public Task<bool> ExistsAsync(string key)
        {
            return Task.FromResult(_cache.TryGetValue(key, out _));
        }
    }
} 